import { RouterRegOptionType } from "../types";

/**类装饰器key标识-路由控制器 */
export const CLASS_KEY_CONTROLLER = "decorator_class:controller";

/**
 * 控制器
 *
 * 请使用使用`export default`方式导出
 * @param {String} prefix 控制器前缀，默认 "/"
 * @param {RouterRegOptionType} routerOptions 控制器参数
 * @example
 * ```javascript
 * +@Controller("/system")
 * +export default class SystemController {}
 * ```
 */
export function Controller(
  prefix?: string,
  routerOptions?: RouterRegOptionType
): (target: any, context?: any) => void {
  // 前缀以/开头
  if (prefix) {
    if (!prefix.startsWith("/")) {
      prefix = "/" + prefix;
    }
  } else {
    prefix = "/";
  }
  // 初始路由参数
  routerOptions = routerOptions || {};
  if (!Array.isArray(routerOptions.middleware)) {
    routerOptions.middleware = [];
  }
  if (typeof routerOptions.ignoreGlobalPrefix !== "boolean") {
    routerOptions.ignoreGlobalPrefix = false;
  }

  return (target: any, _: any) => {
    Reflect.set(target, CLASS_KEY_CONTROLLER, { ...routerOptions, prefix });
  };
}
